package com.whiteape.book;

import android.app.ActivityManager;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.webkit.WebView;

import androidx.annotation.RequiresApi;

import com.kunfei.bookshelf.MApplication;
import com.meituan.android.walle.WalleChannelReader;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.umeng.analytics.MobclickAgent;
import com.umeng.cconfig.RemoteConfigSettings;
import com.umeng.cconfig.UMRemoteConfig;
import com.umeng.cconfig.listener.OnConfigStatusChangedListener;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
//import com.weaction.ddsdk.base.DdSdkHelper;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.receiver.PackageChangedReceiver;
import com.whiteape.book.utils.AppUtils;
import com.whiteape.book.utils.CrashHandler;
import com.whiteape.book.utils.FileUtils;
import com.whiteape.book.utils.LogUtils;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.R;

import java.util.Arrays;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.plugins.RxJavaPlugins;


public class WaApp extends Application {

    private static WaApp instance;
    public static final String NOTIFICATION_CHANNEL_DEFAULT = "channel_default";

    String channel;

    PackageChangedReceiver receiver = new PackageChangedReceiver();
    public static WaApp getInstance() {
        return instance;
    }

    public String getChannel() {
        if(!StringUtils.isEmpty(channel)){
            return channel;
        }
        channel = WalleChannelReader.getChannel(this);
        if (StringUtils.isEmpty(channel)) {
            channel = "d_" + getPackageName() + "_" + AppUtils.getVersionCode(this) + "_" + AppUtils.getVersionName(this);
        }
        return channel;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        MApplication.init(this);
        channel = getChannel();

//        DdSdkHelper.init("1220", "196", "c7893e7344178139d4fe8da0aac9792b",
//                "141553", "35ce0efe5f3cc960b116db227498e238",
//                "7799", "778AFECCFA53C2B2",
//                this, true);

        UMConfigure.setLogEnabled(true);
        LogUtils.init(getApplicationContext());
        UMRemoteConfig.getInstance().setConfigSettings(new RemoteConfigSettings.Builder().setAutoUpdateModeEnabled(false).build());
        //UMRemoteConfig.getInstance().setDefaults(R.xml.cloud_config_parms);
        UMRemoteConfig.getInstance().setOnNewConfigfecthed(new OnConfigStatusChangedListener() {
            @Override
            public void onFetchComplete() {
                LogUtils.d("onFetchComplete " );
                UMRemoteConfig.getInstance().activeFetchConfig();
            }

            @Override
            public void onActiveComplete() {
                String value = UMRemoteConfig.getInstance().getConfigValue("ad_param");
                LogUtils.d("ad_param is " + value);
                //Log.i("UMENG_CC", "value = " + value);
            }
        });

        webviewSetPath(getApplicationContext());
        boolean isShuhuang = AppUtils.isShuhuang(getApplicationContext());
        String umengId = isShuhuang ? WaConstants.UMENG_APPID : WaConstants.UMENG_APP_QILIN;
        UMConfigure.init(this, umengId, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
//        if(!StringUtils.isEmpty(umengId)){
//            LogUtils.d("has umeng id, id=" + umengId);
//            UMConfigure.init(this, umengId, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
//        }else {
//            umengId = WaConstants.UMENG_APP_QILIN;
//            LogUtils.d("do not have umeng id");
//            UMConfigure.init(this, umengId, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
//            ReadSettingManager.getInstance().setUmengId(umengId);
//        }
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.LEGACY_AUTO);
        String adParam = UMRemoteConfig.getInstance().getConfigValue("ad_param");
        LogUtils.d("ad_param 2 is " + adParam);


//        if(channel.startsWith("d_") || new Random().nextInt(10)> 2){
//            UMConfigure.init(this, WaConstants.UMENG_APPID, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
//        }else{
//            UMConfigure.init(this, WaConstants.UMENG_APPID_BAK, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
//        }
        PlatformConfig.setWeixin(WaConstants.WX_APPID, WaConstants.WX_APP_SECRET);
        PlatformConfig.setQQZone(WaConstants.QQ_APPID, WaConstants.QQ_APP_KEY);

        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId
        // 调试时，将第三个参数改为true
        Bugly.init(this, isShuhuang ? WaConstants.BUGLY_APP_ID : WaConstants.BUGLY_APP_ID_QILIN, false);
        Bugly.setAppChannel(this, channel);
        Beta.autoInit = true;
        Beta.autoCheckUpgrade = true;

        RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
//                LogUtil.e("RxJava catch global exception", throwable);
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannelId();
        }
        //设置全局参数，可根据需要进行设置，必须在初始化方法前设置
//        IFLYAdSDK.setParameter(AdKeys.MAIN_PROCESS_NAME, "whiteape");
//
////进行SDK初始化
//        IFLYAdSDK.init(getApplicationContext());
//        TTAdManagerHolder.init(this);
//        initMintegral();
        LogUtils.e("WaApp: " + Thread.currentThread().getName());
        Observable.create(emitter -> backgroundWork())
                .compose(RxUtils::toSimpleSingle)
                .subscribe();

//        FileUtils.migrateBackupFiles();
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        registerReceiver();

    }

    private void registerReceiver(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addDataScheme("package");
        registerReceiver(receiver, intentFilter);
    }
    private void backgroundWork(){
        LogUtils.e("backgroundWork: " + Thread.currentThread().getName());
        if(!ReadSettingManager.getInstance().getMigrateAtVersion112()) {
            FileUtils.migrateBackupFiles();
            //1.1.2开始将以前的设置移过来
            int orderType = ReadSettingManager.getInstance().getCollOrderType();
            //为默认的0 可能是没有才set的，我们直接再set一下，这样SettingsFragment中能自动识别出来
            if (orderType == ReadSettingManager.COLLECTION_ORDER_TYPE_LAST_READ_DESC) {
                ReadSettingManager.getInstance().setCollOrderType(ReadSettingManager.COLLECTION_ORDER_TYPE_LAST_READ_DESC);
            }

            ReadSettingManager.getInstance().setVolumeTurnPage(ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_VOLUME_TO_CHANGE_PAGE));
            ReadSettingManager.getInstance().setFullScreenTurnNextPage(ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_FULLSCREEN_CLICK_TO_CHANGE_PAGE));
            ReadSettingManager.getInstance().setKeepScreenOnWhenReading(ReadSettingManager.getInstance().getReadOtherSettings(ReadSettingManager.READ_OTHER_SETTING_KEEP_SCREEN_ON));
            ReadSettingManager.getInstance().setMigrateAtVersion112(true);

        }

    }

    public void webviewSetPath(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(context);
            String processMain ="com.whiteape.book";
            if (!processMain.equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName+"xxx");
            }else {
//                WebView.setDataDirectorySuffix(processMain+"yyy");
            }
        }
    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }


    /**
     * 创建通知ID
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private void createChannelId() {
        NotificationManager notificationManager = (NotificationManager) WaApp.getInstance().getSystemService(Context.NOTIFICATION_SERVICE);

        //用唯一的ID创建渠道对象
        NotificationChannel readAloudChannel = new NotificationChannel(NOTIFICATION_CHANNEL_DEFAULT,
                WaApp.getInstance().getString(R.string.voice_tts),
                NotificationManager.IMPORTANCE_LOW);
        //初始化channel
        readAloudChannel.enableLights(false);
        readAloudChannel.enableVibration(false);
        readAloudChannel.setSound(null, null);

        //向notification manager 提交channel
        if (notificationManager != null) {
            notificationManager.createNotificationChannels(Arrays.asList(readAloudChannel));
        }
    }


}
